const Result = require("../models/Result");
const {
    Op
} = require('sequelize');
const User = require('../models/User');


exports.getResultById = async function (id) {
    const result = await Result.findByPk(id);
    return result;
}
exports.addResult = async function (resultObj) {
    resultObj = pick(resultObj, 'seq', 'query_result', 'userId');

    validate.validators.userIdExit = async function (value) {
        const result = await User.findByPk(value);
        if (result) {
            return;
        }
        return 'is not exit';
    }
    // 验证规则
    const rule = {
        seq: {
            presence: {
                allowEmpty: false
            },
            type: "string",
            length: {
                minimum: 1,
                maximum: 20
            }

        },
        query_result: {
            presence: {
                allowEmpty: false
            },
        },
        userId: {
            presence: {
                allowEmpty: false,
            },
            numericality: {
                onlyInteger: true,
                strict: false
            },
            classIdExit: true
        }
    }

    try {
        await validate.async(resultObj, rule);
    } catch (err) {
        console.log(err);
    }
    const ins = await Result.create(ResultObj);
    return ins.toJSON();
}

exports.deleteOneResult = async function (resultId) {
    const result = await Student.destroy({
        where: {
            id: resultId
        }
    });
    return result;
}

exports.updateResult = async function (id, resultObj) {
    const result = await Resutl.update(resultObj, {
        where: {
            id
        }
    });
    return result;
}

exports.findAllResult = async function () {
    const results = await Result.findAll();
    return results;
}

exports.getResults = async function (page = 1, limit = 10, userId) {
    const condition = {};
    condition.userId = userId;
    const result = await Result.findAndCountAll({
        // 查指定的列
        attributes: ['seq', 'query_result', 'UserId'],
        where: condition,
        include: [User],
        offset: (page - 1) * limit,
        limit: +limit,
        // 关联表格查询

    });
    return {
        total: result.count,
        datas: JSON.parse(JSON.stringify(result.rows)),
    }

}